package com.nmgydy.admin.controller;

import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nmgydy.beans.ListBean;
import com.nmgydy.beans.ResultBean;
import com.nmgydy.model.*;
import com.nmgydy.util.BpmnUtil;
import com.nmgydy.util.Functions;
import com.nmgydy.util.HibernateDao;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("/admin/admin")
public class AAdminController {

	@Resource
	private HibernateDao hibernateDao;

	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/admin/admin/list";
	}

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add() {
		return "/admin/admin/add";
	}

	@RequestMapping(value = "edit", method = RequestMethod.GET)
	public String edit(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/admin/admin/edit";
	}

	@RequestMapping(value = "editPassword", method = RequestMethod.GET)
	public String editPassword(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/admin/admin/editPassword";
	}
	
	@RequestMapping(value = "search", method = RequestMethod.GET)
	public String search(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/admin/admin/search";
	}
	
	@RequestMapping(value = "listData", method = RequestMethod.POST)
	@ResponseBody
	public String listData(HttpServletRequest request, HttpServletResponse response, Model model) {
		String pageSize = request.getParameter("pageSize");
		String pageIndex = request.getParameter("pageIndex");
		String sortField = request.getParameter("sortField");
		String sortOrder = request.getParameter("sortOrder");

		String hql = "from Admin a where a.id=a.id ";
		Map<String, Object> params = new HashMap<String, Object>();
		
		String username = request.getParameter("username");
		if (!Functions.isEmpty(username)) {
			hql += " and username like :username";
			params.put("username", "%" + username + "%");
		}

		String truename = request.getParameter("truename");
		if (!Functions.isEmpty(truename)) {
			hql += " and truename like :truename";
			params.put("truename", "%" + truename + "%");
		}
		Boolean sorted = !(sortField == null || "".equals(sortField) || sortOrder == null || "".equals(sortOrder));
		if (sorted) {
			hql += " order by :sortField :sortOrder";
			params.put("sortField", sortField);
			params.put("sortOrder", sortOrder);
		}else{
			hql += " order by id desc";
		}
		
		Boolean paged = !(pageSize == null || "".equals(pageSize) || pageIndex == null || "".equals(pageIndex));
		if (paged) {
			long total = hibernateDao.count(hql, params);
			List<?> list = hibernateDao.list(hql, params, Integer.parseInt(pageIndex) + 1, Integer.parseInt(pageSize));
			return JSON.toJSONString(new ListBean(list,total));
		} else {
			long total = hibernateDao.count(hql, params);
			List<?> list = hibernateDao.list(hql, params);
			return JSON.toJSONString(new ListBean(list,total));
		}
	}
	
	//添加用户
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public String save(Admin admin,HttpServletRequest request, HttpServletResponse response, Model model) {

		if(Functions.isEmpty(admin.getUsername())){
			return JSON.toJSONString(ResultBean.failure("username不能为空"));
		}
		if(Functions.isEmpty(admin.getPassword())){
			return JSON.toJSONString(ResultBean.failure("password不能为空"));
		}
		if(Functions.isEmpty(admin.getTruename())){
			return JSON.toJSONString(ResultBean.failure("truename不能为空"));
		}
		if(admin.getRoleIds() == null){
			return JSON.toJSONString(ResultBean.failure("roleId is null"));
		}
		if(admin.getDepartmentIds() == null){
			return JSON.toJSONString(ResultBean.failure("departmentIds is null"));
		}

		//角色
		int[] ids = Arrays.stream(admin.getRoleIds().split(",")).mapToInt(Integer::parseInt).toArray();
		Integer[] idsArray = Arrays.stream(ids).boxed().toArray(Integer[]::new);
		String hql = "from Role where id in (:ids)";
		Map<String,Object> params = new HashMap<>();
		params.put("ids",idsArray);
		List<?> list = hibernateDao.list(hql,params);
		if(list.size() <= 0){
			return JSON.toJSONString(ResultBean.failure("role not found."));
		}
		String[] roleNameArr = new String[list.size()];
		for(int i=0;i<list.size();i++){
			Role role = (Role) list.get(i);
			roleNameArr[i] = role.getName();
		}
		String roleNames = String.join(",",roleNameArr);
		admin.setRoleNames(roleNames);

		//部门
		ids = Arrays.stream(admin.getDepartmentIds().split(",")).mapToInt(Integer::parseInt).toArray();
		idsArray = Arrays.stream(ids).boxed().toArray(Integer[]::new);
		hql = "from Department where id in (:ids)";
		params = new HashMap<>();
		params.put("ids",idsArray);
		list = hibernateDao.list(hql,params);
		if(list.size() <= 0){
			return JSON.toJSONString(ResultBean.failure("role not found."));
		}
		String[] departmentNameArr = new String[list.size()];
		for(int i=0;i<list.size();i++){
			Department department = (Department) list.get(i);
			departmentNameArr[i] = department.getName();
		}
		String departmentNames = String.join(",",departmentNameArr);
		admin.setDepartmentNames(departmentNames);

		boolean flag = hibernateDao.save(admin);
		if(flag){
			return JSON.toJSONString(ResultBean.success("用户管理添加成功"));
		}
		return JSON.toJSONString(ResultBean.failure("用户管理添加失败"));
		
	}
	
	//编辑用户管理
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(Admin admin,HttpServletRequest request, HttpServletResponse response, Model model) {
		if(admin.getId() == null){
			return JSON.toJSONString(ResultBean.failure("id不能为空"));
		}
		if(Functions.isEmpty(admin.getUsername())){
			return JSON.toJSONString(ResultBean.failure("username不能为空"));
		}
		if(Functions.isEmpty(admin.getTruename())){
			return JSON.toJSONString(ResultBean.failure("不能为空"));
		}
		if(admin.getRoleIds() == null){
			return JSON.toJSONString(ResultBean.failure("roleId is null"));
		}
		if(admin.getDepartmentIds() == null){
			return JSON.toJSONString(ResultBean.failure("departmentIds is null"));
		}

		//角色
		int[] ids = Arrays.stream(admin.getRoleIds().split(",")).mapToInt(Integer::parseInt).toArray();
		Integer[] idsArray = Arrays.stream(ids).boxed().toArray(Integer[]::new);
		String hql = "from Role where id in (:ids)";
		Map<String,Object> params = new HashMap<>();
		params.put("ids",idsArray);
		List<?> list = hibernateDao.list(hql,params);
		if(list.size() <= 0){
			return JSON.toJSONString(ResultBean.failure("role not found."));
		}
		String[] roleNameArr = new String[list.size()];
		for(int i=0;i<list.size();i++){
			Role role = (Role) list.get(i);
			roleNameArr[i] = role.getName();
		}
		String roleNames = String.join(",",roleNameArr);
		admin.setRoleNames(roleNames);

		//部门
		ids = Arrays.stream(admin.getDepartmentIds().split(",")).mapToInt(Integer::parseInt).toArray();
		idsArray = Arrays.stream(ids).boxed().toArray(Integer[]::new);
		hql = "from Department where id in (:ids)";
		params = new HashMap<>();
		params.put("ids",idsArray);
		list = hibernateDao.list(hql,params);
		if(list.size() <= 0){
			return JSON.toJSONString(ResultBean.failure("role not found."));
		}
		String[] departmentNameArr = new String[list.size()];
		for(int i=0;i<list.size();i++){
			Department department = (Department) list.get(i);
			departmentNameArr[i] = department.getName();
		}
		String departmentNames = String.join(",",departmentNameArr);
		admin.setDepartmentNames(departmentNames);

		hql = "from Admin where id=:id";
		params = new HashMap<>();
		params.put("id",admin.getId());
		list = hibernateDao.list(hql,params);
		if(list.size() <= 0){
			return JSON.toJSONString(ResultBean.failure("Admin not found."));
		}
		Admin adminFromDb = (Admin) list.get(0);
		admin.setPassword(adminFromDb.getPassword());
		boolean flag = hibernateDao.update(admin);
		if(flag){
			return JSON.toJSONString(ResultBean.success("用户更新成功"));
		}
		return JSON.toJSONString(ResultBean.failure("用户更新失败"));
	}

	//修改密码
	@RequestMapping(value = "updatePassword", method = RequestMethod.POST)
	@ResponseBody
	public String updatePassword(Admin admin,HttpServletRequest request, HttpServletResponse response, Model model) {
		if(admin.getId() == null){
			return JSON.toJSONString(ResultBean.failure("id不能为空"));
		}
		if(Functions.isEmpty(admin.getPassword())){
			return JSON.toJSONString(ResultBean.failure("password不能为空"));
		}

		String hql = "from Admin where id=:id";
		Map<String,Object> params = new HashMap<>();
		params.put("id",admin.getId());
		List<?> list = hibernateDao.list(hql,params);
		if(list.size() <= 0){
			return JSON.toJSONString(ResultBean.failure("role not found."));
		}
		Admin adminFromDb = (Admin) list.get(0);
		adminFromDb.setPassword(admin.getPassword());
		boolean flag = hibernateDao.update(adminFromDb);
		if(flag){
			return JSON.toJSONString(ResultBean.success("密码修改成功"));
		}
		return JSON.toJSONString(ResultBean.failure("密码修改失败"));
	}


	//删除用户管理
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(HttpServletRequest request, HttpServletResponse response, Model model) {
		String ids = request.getParameter("ids");
		if (ids != null && !"".equals(ids)) {
			ids = ids.replace("'", "");
		} else {
			return JSON.toJSONString(ResultBean.failure("ID集合信息不存在!"));
		}
		String[] idStrs = ids.split(",");
		if(idStrs.length <= 0){
			return JSON.toJSONString(ResultBean.failure("请正确选择记录!"));
		}
		List<Integer> delIdList = new ArrayList<Integer>(idStrs.length);
		for(String id:idStrs){
			delIdList.add(Integer.parseInt(id));
		}
		Session session = null;
		Transaction transaction = null;
		try{
			session = hibernateDao.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			String deleteHql = "delete from Admin where id in (:ids)";
			int row = session.createQuery(deleteHql).setParameterList("ids", delIdList).executeUpdate();
			transaction.commit();
			System.out.println("删除用户管理信息成功 -- 受影响行数：" + row);
			return JSON.toJSONString(ResultBean.success("删除成功，删除成功条数" + row + "条。!"));
		} catch (Exception e) {
			e.printStackTrace();
			if (transaction != null) {
				transaction.rollback();
			}
			return JSON.toJSONString(ResultBean.failure("删除失败!"));
		} finally {
			session.close();
		}
	}

	@RequestMapping(value = "roleList")
	@ResponseBody
	public String roleList(HttpServletRequest request, HttpServletResponse response, Model model) {
		String hql = "from Role";
		List<?> list = hibernateDao.list(hql);
		return JSON.toJSONString(list);
	}

	@RequestMapping(value = "departmentList")
	@ResponseBody
	public String departmentList(HttpServletRequest request, HttpServletResponse response, Model model) {
		String hql = "from Department";
		List<?> list = hibernateDao.list(hql);
		return JSON.toJSONString(list);
	}

	@RequestMapping(value = "getMenu", method = RequestMethod.POST)
	@ResponseBody
	public String getMenu(HttpServletRequest request, HttpServletResponse response, Model model) {
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		int[] ids = Arrays.stream(admin.getRoleIds().split(",")).mapToInt(Integer::parseInt).toArray();
		Integer[] idsArray = Arrays.stream(ids).boxed().toArray(Integer[]::new);
		String sql = "select m.* from cn_module m,cn_module_role r where m.id=r.moduleId" +
				" and r.roleId in (:ids) and m.level<=2 group by m.id order by sn asc";
		//System.out.println(JSON.toJSONString(ids));
		Map<String,Object> params = new HashMap<>();
		params.put("ids",idsArray);
		List<?> sList = hibernateDao.sqlList(sql,params);
		//System.out.println(JSON.toJSONString(sList));;
		List<Module> list = new ArrayList<>();
		for(int i=0;i<sList.size();i++){
			Map<String,Object> rowMap = (Map<String, Object>) sList.get(i);
			Module module = new Module();
			module.setId((Integer) rowMap.get("id"));
			module.setSn((String) rowMap.get("sn"));
			module.setName((String) rowMap.get("name"));
			module.setUrl((String) rowMap.get("url"));
			module.setIconCls((String) rowMap.get("iconCls"));
			module.setFid((Integer) rowMap.get("fid"));
			module.setLevel((Integer) rowMap.get("level"));
			list.add(module);
		}

		//一级栏目
		JSONArray jsonArray = new JSONArray();
		for(int i=0;i<list.size();i++){
			Module module = list.get(i);
			if(module.getLevel() != 1){
				continue;
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("uid",module.getId());
			jsonObject.put("id",module.getSn());
			jsonObject.put("text",module.getName());
			jsonObject.put("iconCls",module.getIconCls());
			jsonArray.add(jsonObject);
		}
		//二级栏目
		for(int k=0;k<jsonArray.size();k++){
			JSONObject jsonObject = jsonArray.getJSONObject(k);
			JSONArray childrenArray = new JSONArray();
			for(int i=0;i<list.size();i++) {
				Module module = list.get(i);
				if(module.getLevel() != 2){
					continue;
				}
				if(module.getFid().equals(jsonObject.getInteger("uid"))){
					JSONObject childObject = new JSONObject();
					childObject.put("uid",module.getId());
					childObject.put("id", module.getSn());
					childObject.put("text", module.getName());
					childObject.put("url", module.getUrl());
					childObject.put("iconCls", module.getIconCls());
					childrenArray.add(childObject);
				}
			}
			if(childrenArray.size() > 0){
				jsonObject.put("children",childrenArray);
			}
		}
		return JSON.toJSONString(jsonArray,true);
	}

	@RequestMapping(value = "saveBpmn")
	@ResponseBody
	public String saveBpmn(String caseType,HttpServletRequest request, HttpServletResponse response, Model model) {
		if(Functions.isEmpty(caseType)){
			return "caseType is null";
		}
		BpmnUtil.saveBpmn(hibernateDao,caseType);
		return "success";
	}

	@RequestMapping(value = "updateHistory")
	@ResponseBody
	public String updateHistory(String caseType,HttpServletRequest request, HttpServletResponse response, Model model) {
		String hql = "from Court";
		List<Court> courtList = (List<Court>) hibernateDao.list(hql);
		for(int i=0;i<courtList.size();i++){
			Court court = courtList.get(i);
			hql = "from MoveHistory where courtId="+court.getId()+" order by id asc";
			List<MoveHistory> historyList = (List<MoveHistory>) hibernateDao.list(hql);
			for(int j=0;j<historyList.size();j++){
				MoveHistory history = historyList.get(j);
				history.setCourtName(court.getName());
				history.setCourtNumber(court.getNumber());
				if(j==0){
					history.setLastHistoryId(0);
					history.setLastTaskId(0);
					history.setLastTaskName("————");
					history.setLastTotDays(0);
					history.setLastCurDays(0);
				}else{
					MoveHistory lastHistory = historyList.get(j-1);
					history.setLastHistoryId(lastHistory.getId());
					history.setLastTaskId(lastHistory.getTaskId());
					history.setLastTaskName(lastHistory.getTaskName());
					history.setLastTotDays(lastHistory.getTotDays());
					history.setLastCurDays(lastHistory.getCurDays());
				}
				hibernateDao.update(history);
			}
		}

		return "success";
	}

}
